package first.niuke.simple;

/**
 * @ClassName NC105
 * @description:
 * @author: 荣燊
 * @create: 2021-04-07 21:39
 **/
public class NC105 {
    public static void main(String[] args) {
        int[] nums = {-2, 1, 2};
        int target = 2;
//        HashMap<Integer, Integer> map = new HashMap<>();
//        for (int i=0; i<nums.length; i++) {
//            map.put(nums[i], i);
//        }
//        System.out.println(map);

        System.out.println(search(nums, target));
    }

    public static int search (int[] nums, int target) {
        // write code here
        //二分查找，速度更快
        int i = 0;
        int j = nums.length-1;

        while (i <= j) {
            int tmp = (i + j) / 2;
            if (nums[tmp] == target) {
                while (tmp != 0 && (nums[tmp-1] == nums[tmp])) {
                    tmp--;
                }
                return tmp;
            } else if (nums[tmp] > target) {
                j = tmp-1;
            } else {
                i = tmp+1;
            }
        }
        return -1;
    }
}
